
package com.xebest.web.controller.vensys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.common.util.imgupload.UploadFileHttpUtil;
import com.xebest.config.ParamConfig;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.web.form.XeVenAreaRoleForm;
import com.xebest.web.form.XeVenStoreRoleForm;
import com.xebest.web.service.XeVenAreaRoleService;
import com.xebest.web.service.XeVenStoreRoleService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenAreaRoleView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 系统设置中心
 *
 * @author 李贝贝
 */
@RestController
@RequestMapping("venSys")
public class XeVenSysSetController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenSysSetController.class);//日志记录类

    @Autowired
    private XeVenStoreRoleService xeVenStoreRoleService;//仓库角色权限业务操作

    @Autowired
    private XeVenAreaRoleService xeVenAreaRoleService;//区域角色权限业务操作

    @Autowired
    private XeBaseUtil xeBaseUtil;//缓存操作类

    @Autowired
    private ParamConfig paramConfig;//公共参数配置

    /**
     * 根据用户标识查找已经分配的角色仓库
     *
     * @author 李贝贝
     */
    @RequestMapping("queryRoleStore")
    public @ResponseBody
    BaseResponse queryRoleStore(@RequestBody XeVenStoreRoleForm form) {
        // 1、验证参数
        if (null == form || null == form.getRoleId())
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        // 2、拼装参数
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());//获取供应商编码
        // 3、输出结果
        List<Map<String, Object>> entities = xeVenStoreRoleService.queryRoleStore(form);
        Map<String, Object> rm = new HashMap<String, Object>();
        rm.put("roleStoreData", entities);
        return sendAjaxOK(rm);
    }

    /**
     * 保存仓库角色权限
     *
     * @author 李贝贝
     */
    @RequestMapping("saveRS")
    public @ResponseBody
    BaseResponse saveRoleStore(@RequestBody XeVenStoreRoleForm form) {
        log.info("保存仓库角色请求参数为：{}", JSON.toJSONString(form));
        //1、验证参数
        if (null == form.getRoleId() || null == form.getStoreIdArr()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //2、拼装参数
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());//获取供应商编码
        //3、输出结果
        int result = 0;
        try {
            result = xeVenStoreRoleService.updateStoreRole(form);
            log.info("成功保存 {} 条仓库角色权限!", result);
        } catch (Exception e) {
            log.error("保存仓库角色权限异常：{}", e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 暂时没用 2017年9月20号
     * 修改仓库角色仓库权限 策略：先删除再添加
     *
     * @author 李贝贝
     */
    @RequestMapping("editRS")
    public @ResponseBody
    BaseResponse updateRoleStore(@RequestBody XeVenStoreRoleForm form) {
        log.info("修改仓库角色请求参数为：{}", JSON.toJSONString(form));
        //1、验证参数
        if (null == form.getRoleId() || null == form.getStoreIdArr()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //2、拼装参数
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());//获取供应商编码
        //3、输出结果
        int result = 0;
        try {
            result = xeVenStoreRoleService.updateStoreRole(form);
            log.info("成功修改 {} 条仓库角色权限!", result);
        } catch (Exception e) {
            log.error("修改仓库角色权限异常：{}", e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }


    /**
     * 根据角色标识查找已经分配的角色区域权限
     *
     * @author 李贝贝
     */
    @RequestMapping("queryRoleArea")
    public @ResponseBody
    BaseResponse queryRoleArea(@RequestBody XeVenAreaRoleForm form) {
        // 1、验证参数
        if (null == form || null == form.getRoleId())
            return sendAjaxError(BASEMessage.PARAM_ERROR);

        Map<String, Object> rm = new HashMap<String, Object>();
        try {
            //获取用户登录信息
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            // 2、拼装参数
            form.setUserCode(userInfo.getUserCode());//获取供应商编码
            // 3、输出结果
            XeVenAreaRoleView entities = new XeVenAreaRoleView();

            entities = xeVenAreaRoleService.queryRoleArea(form);
            log.debug(JSON.toJSONString(entities));
            rm.put("roleAreaData", entities);

        } catch (Exception e) {
            log.error("查询角色区域权限异常：{}", e);
            return sendAjaxError();
        }

        return sendAjaxOK(rm);
    }

    /**
     * 暂时没用 2017年9月20号
     * 保存区域角色权限
     *
     * @author 李贝贝
     */
    @RequestMapping("saveRoleArea")
    public @ResponseBody
    BaseResponse saveRoleArea(@RequestBody XeVenAreaRoleForm form) {
        log.info("保存区域角色请求参数为：{}", JSON.toJSONString(form));
        //1、验证参数
        if (null == form.getRoleId() || null == form.getAreaIdArr()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //2、拼装参数
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());//获取供应商编码
        //3、输出结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            resultMap = xeVenAreaRoleService.insertAreaRole(form);
            log.info("成功保存 {} 条区域角色权限!", resultMap.get("result"));

        } catch (Exception e) {
            log.error("保存区域角色权限异常：{}", e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 修改区域角色权限 策略：先删除再添加
     * 修改内容 service层修改为直接调用添加角色区域方法
     *
     * @author 李贝贝
     * @author 杜春静
     */
    @RequestMapping("editRoleArea")
    public @ResponseBody
    BaseResponse updateRoleArea(@RequestBody XeVenAreaRoleForm form) {
        log.info("修改区域角色请求参数为：{}", JSON.toJSONString(form));
        //1、验证参数
        if (null == form.getRoleId()) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //2、拼装参数
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());//获取供应商编码
        //3、输出结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            resultMap = xeVenAreaRoleService.insertAreaRole(form);
            log.info("成功修改 {} 条区域角色权限!", resultMap.get("result"));
        } catch (Exception e) {
            log.error("修改区域角色权限异常：{}", e);
            return sendAjaxError();
        }
        return sendAjaxOK();
    }


    /**
     * 区域id获取区域
     * <p>
     * -1 查询国家
     * 0 查询所有省
     * 省id  查询所有市
     * 市id 查询所有区
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryArea")
    public @ResponseBody
    BaseResponse queryArea(@RequestBody XeVenAreaRoleForm form) {
        // 1、验证参数
        if (null == form || null == form.getRegionId())
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        try {
            //2.根据父id获取下级区域信息
            JSONArray array = xeBaseUtil.getChildArea(form.getRegionId());
            Map<String, Object> rm = new HashMap<String, Object>();
            rm.put("areaArray", array);
            return sendAjaxOK(rm);
        } catch (Exception e) {
            log.error("区域id获取区域失败异常 {}", e);
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }

    }

    /**
     * 获取所有分类信息
     *
     * @author 赵盼飞
     */
    @RequestMapping("queryProCategory")
    public @ResponseBody
    BaseResponse queryProAllCategory() {

        try {
            //1.获取所有分类
            JSONArray array = xeBaseUtil.getAllCategory();
            Map<String, Object> rm = new HashMap<String, Object>();
            rm.put("proCategory", array);
            return sendAjaxOK(rm);
        } catch (Exception e) {
            log.error("获取所有分类信息异常 {}", e);
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }

    }

    /**
     * 上传图片
     */
    @RequestMapping("imgUpload")
    @ResponseBody
    public BaseResponse manImgUpload(HttpServletRequest request, String fileType, String zoom) {
        log.info("============上传合同图片[开始]");
        try {
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            if (commonsMultipartResolver.isMultipart(request)) { // 判断是否是上传
                List<MultipartFile> fileUploadss = ((MultipartHttpServletRequest) request).getFiles("imgFiles");
                if (fileUploadss != null && fileUploadss.size() >= 0) {
                    String uploadImgUrl = paramConfig.getUpoladImgUrl();
                    JSONArray imgInfoList = new JSONArray();
                    for (MultipartFile fileUpload : fileUploadss) {
                        if (!fileUpload.isEmpty()) {
                            // 生成上传文件名称
                            String imgName = UploadFileHttpUtil.getUrlName();
                            // 获取图片的宽度和高度自动裁剪图片尺寸
                            JSONObject obj = UploadFileHttpUtil.imgWidthAndheight(fileUpload);
                            int width = Integer.parseInt(String.valueOf(obj.get("width")));
                            int height = Integer.parseInt(String.valueOf(obj.get("height")));
                            JSONObject imgInfo = UploadFileHttpUtil.upLoadImgVen(imgName, fileType, zoom, fileUpload, uploadImgUrl, width, height);
                            imgInfoList.add(imgInfo);
                        }
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("imgInfoList", imgInfoList);
                    //图片域名
                    map.put("picServer", paramConfig.getImgUrl());
                    log.info("============上传合同图片[结束],成功上传图片{}张", fileUploadss.size());
                    return sendAjaxOK(map);
                }
            }
        } catch (Exception e) {
            log.error("============上传图片[参数异常]{}", e);
        }

        return sendAjaxError(BASEMessage.PARAM_ERROR);
    }


}